var i = 1;
var totalPage = "";
var leftLi = null;
var rightLi = null;
var resultLeft = 1;
var resultRight = 1;
var arr = [];
$(function(){
	queryProvince();
	$("#provinceId").change(queryCity);
	$("#cityId").change(queryCounty);
	var token=localStorage.getItem("token");
	gridObj = $.fn.bsgrid.init('g_tabYeh', {
		ajaxType : 'get',
		url :  server_url+'/rest/supplyManage/supplyAreaList.do?ran=' + Math.random() + '&token=' + token,
		autoLoad : true,
		pageSizeSelect : true,
		stripeRows : true,
		pageSize : 10,
		displayBlankRows : false,
		isProcessLockScreen : true,
		rowSelectedColor : false,
		showPageToolbar:true,
		rowHoverColor:true
	});	
	/*InitSupplyAreaData(i);
	$("#g_tabYeh_pt_nextPage").live("click",function(){
		i++;
		if(i>totalPage){
			i = totalPage;
			return;
		}else{
			InitSupplyAreaData(i);
		}	
	});
	$("#g_tabYeh_pt_prevPage").live("click",function(){
		i--;
		if(i<1){
			i = 1;
			return;
		}else{
			InitSupplyAreaData(i);
		}
	});
	$("#g_tabYeh_pt_lastPage").live("click",function(){
		i = totalPage;
		InitSupplyAreaData(i);
	});
	$("#g_tabYeh_pt_firstPage").live("click",function(){
		i = 1;
		InitSupplyAreaData(i);
	});
	$("#g_tabYeh_pt_gotoPage").live("click",function(){
		if($("#g_tabYeh_pt_gotoPageInput").val()>totalPage){
			return;
		}else{
			i = $("#g_tabYeh_pt_gotoPageInput").val();
			InitSupplyAreaData(i);
		}	
	});*/
	/*$("#g_tabYeh tr").each(function(i,obj){
		var length = parseInt($(this).find("td:eq(0)").text());
		$(this).find("td:eq(0)").remove();
		//console.log(length);
		if(!isNaN(length) && length > 1){
			var next = this;
			$(next).find("td:lt(2)").attr("rowspan",length);
			$(next).find("td:gt(4)").attr("rowspan",length);
			for(var i =0 ;i<length -1 ;i++){
				$(next).next().find("td:lt(2)").remove();
				$(next).next().find("td:gt(3)").remove();
				next = $(next).next();
			}
		}
	});*/
    $('#del').click(function(){
    	rightLi = $('#selectedCountyId').find("li").length; 
    	console.log(rightLi);
    	if(resultRight-1 == rightLi){
			alert("不能都删除，至少留一条数据！");
			return;
		}else{
			$('#selectedCountyId li').each(function(i,data){
	    		if(data.getAttribute("class") == "active2"){
	    			data.setAttribute("onclick","selectEvents(this);");
	        		data.setAttribute("style","cursor: pointer; background:");
	        		data.setAttribute("class","");
	        		$('#countyId').append(data);
	    			document.getElementById("del").disabled = true;
	    			resultRight = 1;
	    		}
	    	});
		}
    });
    $('#addInsert').click(function(){
    	$('#countyId li').each(function(i,data){
    		console.log(data.getAttribute("class"));
    		if(data.getAttribute("class") == "active2"){
    			data.setAttribute("onclick","selectEventDels(this);");
    			data.setAttribute("style","cursor: pointer; background:");
    			data.setAttribute("class","");
    			$('#selectedCountyId').append(data);
    			document.getElementById("addInsert").disabled = true;
    			resultLeft = 1;
    		}
    	});
    });
});
function queryProvince(){
	$("#provinceId").empty();
	var html="<option value='' selected='selected'>"+"省/直辖市"+"</option>";
	$(html).appendTo("#provinceId");
	$.ajax({
		type:"get",
		url:server_url+"rest/areaManager/getProvince.do?token="+$("body").data("token"),
		async:false,
		success:function(data){
			for(var i=0;i<data.data.length;i++){
				var html="<option value="+data.data[i].areaId+">"+data.data[i].areaName+"</option>";
				$(html).appendTo("#provinceId");
			}
		}
	});
	queryCity();
};

function queryCity(){
	$.ajax({
		type:"get",
		url:server_url+"rest/areaManager/getByParent.do?token="+$("body").data("token"),
		data:{
			parentId:$("#provinceId").val()
		},
		async:false,
		success:function(data){
			$("#cityId").empty();
			if(data.data!=null){
				var html="<option value='' selected='selected'>"+"市/区"+"</option>";
				$(html).appendTo("#cityId");
				for(var i=0;i<data.data.length;i++){
					var html="<option value="+data.data[i].areaId+">"+data.data[i].areaName+"</option>";
					$(html).appendTo("#cityId");
				};
			}else{
				var html="<option value='' selected='selected'>"+"市/区"+"</option>";
				$(html).appendTo("#cityId");
			}
		}
	});
	queryCounty();
};
function queryCounty(){
	$("#countyId").empty();
	var ids = "";
	console.log(arr);
	$.ajax({
		type:"get",
		url:server_url+"rest/areaManager/getByParent.do?token="+$("body").data("token"),
		data:{
			parentId:$("#cityId").val()
		},
		async:false,
		success:function(data){
			$("#countyId").empty();
			arr.splice(0,arr.length);
			document.getElementById("countyId").setAttribute("value",1);
			document.getElementById("addInsert").disabled = true;
			resultLeft = 1;
			if(data.data != null){
				
				for(var i=0;i<data.data.length;i++){
					arr.push(data.data[i].areaId);
				}
			}
		}
	});
	for(var j=0;j<$("#selectedCountyId li").length;j++){
		console.log($("#selectedCountyId li")[j].getAttribute("value"));
		ids += $("#selectedCountyId li")[j].getAttribute("value")+",";
	}
	var saleAreaId = ids.split(",");
	replaceEmptyItem(saleAreaId);
	for(var i=0;i<saleAreaId.length;i++){
		for(var j=0;j<arr.length;j++){
			if(saleAreaId[i]==arr[j]){
				arr.remove(arr[j]);
			}else{
				arr;
			}
		}
	}
	for(var i=0;i<arr.length;i++){
		$.ajax({
			type:"get",
			url:server_url+"rest/areaManager/getAreaInfoByAreaId.do?token="+$("body").data("token"),
			data:{
				areaId:arr[i]
			},
			success:function(data){
				if(data.data != null){
						var html ="<li class='' style='cursor: pointer; background:' onclick='selectEvents(this);' value="+data.data.areaId+">"+data.data.areaName+";</li>";
						$(html).appendTo("#countyId");
				}
				
			}
		});
	}
	
};
Array.prototype.indexOf = function(val) {
	for (var i = 0; i < this.length; i++) {
	if (this[i] == val) return i;
	}
	return -1;
};
Array.prototype.remove = function(val) {
	var index = this.indexOf(val);
	if (index > -1) {
	this.splice(index, 1);
	}
};
//添加
function selectEvents(e){
	if(e.style.background == 'rgb(255, 90, 0)'){
        e.style.background = '';
        $(e).removeClass("active2");
        document.getElementById("countyId").setAttribute("value",--resultLeft);
    }else{
        e.style.background = '#ff5a00';
        document.getElementById("countyId").setAttribute("value",++resultLeft);
        document.getElementById("addInsert").disabled = false;
        $(e).addClass("active2");
       
       
    }
	 cancelDisabled("left");
};
//删除
function selectEventDels(e){
	if(e.style.background == 'rgb(255, 90, 0)'){
        e.style.background = '';
        $(e).removeClass("active2");
        document.getElementById("selectedCountyId").setAttribute("value",--resultRight);
    }else{
        e.style.background = '#ff5a00';
        document.getElementById("selectedCountyId").setAttribute("value",++resultRight);
        document.getElementById("del").disabled = false;
        $(e).addClass("active2");
       
    } 
	 cancelDisabled("right");
};
function cancelDisabled(str){
	if(str=="left"){
		if(document.getElementById("countyId").getAttribute("value")>1){
			document.getElementById("addInsert").disabled = false;
		}else{
			document.getElementById("addInsert").disabled = true;
		}	
	}else{
		if(document.getElementById("selectedCountyId").getAttribute("value")>1){
			document.getElementById("del").disabled = false;
		}else{
			document.getElementById("del").disabled = true;
		}	
	}
	
};
/*function InitSupplyAreaData(i){
	var userdatas = [];
	userdatas.success = true;
	userdatas.curPage = i;
	var data_formate = '{"data":{"total":9999999999999999999999999999,"curPage":'+i+',"rows":';
	var parms = {};
	parms["supplyName"] = $("#supplyName").val();
	$.ajax({
		type : 'post',
		url : server_url+'/rest/supplyManage/supplyAreaList.do?ran='+Math.random()+"&token="+token,
		async:false,
		data:parms,
		success : function(data) {
			if(data.retCode=="0000"||data.retCode=="0002"){
				var datastr = "";
				if(data.data!=null){
					datastr=data.data;
				}
				var treejson = JSON.stringify(datastr);
				data_formate = data_formate+ treejson;
			}
			else{
				easyDialog.open({
					  container : {
						  header : '提示',
					    content : data.retMsg
					  },
					  autoClose : 2000
					});
				
			} 
			
		}
	});
	data_formate = data_formate + '},"retCode":"0000","retMsg":"\u64cd\u4f5c\u6210\u529f"}';
	userdata = $.parseJSON(data_formate);
	var sdfs = getItemData(userdata.data.rows);
	//console.log(sdfs);
	userdatas.totalRows = sdfs.length;
	userdatas.data = sdfs;
	gridObj.loadGridData('json', userdatas);
	totalPage = $("#g_tabYeh_pt_totalPages").text();
	show();
}*/
/*function getItemData(datas) {
	var sdfs = [];
	if (typeof (datas) == "object") {
		$.each(datas.rows, function(i, data) {
			var p = {};
			p.id = data.id;
			p.supplyId = data.supplyId;
			p.supplyName = data.supplyName;
			p.supplyAreaName = '<div id="firstpane" class="menu_list">';
			var areaIds = data.areaId;
			var areaId = areaIds.split(",");
			replaceEmptyItem(areaId);
				for(var k=0;k<areaId.length;k++){
					$.ajax({
						url:server_url+"/rest/supplyManage/getAreaName.do?areaId="+areaId[k],
						type:"get",
						async:false,
						success:function(datas){
							if(datas.retCode=="0000"){
								if(areaId.length>1){
									if(datas.data[0].cityName =='市辖区'){
										
										p.supplyAreaName +='<p class="menu_head">'+datas.data[0].provinceName + "-" + datas.data[0].countyName+'</p><div class="menu_body"><a href="javascript:editSupplyArea( '+data.id+','+areaId[k]+');">编辑</a><a href="javascript:delSupplyArea( '+data.id+','+areaId[k]+');">删除</a></div>';
									}else{
										p.supplyAreaName += '<p class="menu_head">'+datas.data[0].provinceName+ "-" + datas.data[0].cityName+"-"+datas.data[0].countyName+'</p><div class="menu_body"><a href="javascript:editSupplyArea( '+data.id+','+areaId[k]+');">编辑</a><a href="javascript:delSupplyArea( '+data.id+','+areaId[k]+');">删除</a></div>';
									}
								}else if(areaId.length==1){
									if(datas.data[0].cityName =='市辖区'){
									
									p.supplyAreaName +='<p class="menu_head">'+datas.data[0].provinceName + "-" + datas.data[0].countyName+'</p><div class="menu_body"><a href="javascript:editSupplyArea( '+data.id+','+areaId[k]+');">编辑</a></div>';
								}else{
									p.supplyAreaName += '<p class="menu_head">'+datas.data[0].provinceName+ "-" + datas.data[0].cityName+"-"+datas.data[0].countyName+'</p><div class="menu_body"><a href="javascript:editSupplyArea( '+data.id+','+areaId[k]+');">编辑</a></div>';
								}
						}		
							}else{
								easyDialog.open({
									  container : {
										  header : '提示',
									      content : data.retMsg
									  },
									  autoClose : 2000
									});	
							}
						}
					})
				}
			p.supplyAreaName += '</div>';
				sdfs.push(p);
			
		});
		}
	return sdfs;
};*/
function operate(record, rowIndex, colIndex, options) {
    return '<a href="javascript:editSupplyArea(\'' + gridObj.getRecordIndexValue(record, 'id') + '\');">编辑</a>';
};
function supplyAreaName(record, rowIndex, colIndex, options){
	var areaIds = record.areaId;
	var areaId = areaIds.split(",");
	replaceEmptyItem(areaId);
	var areaNameStr = "<div>"
	for(var k=0;k<areaId.length;k++){
		$.ajax({
			url:server_url+"/rest/supplyManage/getAreaName.do?areaId="+areaId[k],
			type:"get",
			async:false,
			success:function(msg){
				if(msg.retCode=="0000"){
					if(areaId.length>1){
						if(msg.data[0].cityName =='市辖区'){
							
							areaNameStr +='<p>'+msg.data[0].provinceName + "-" + msg.data[0].countyName+'</p></div>';
						}else{
							areaNameStr += '<p>'+msg.data[0].provinceName+ "-" + msg.data[0].cityName+"-"+msg.data[0].countyName+'</p></div>';
						}
					}else if(areaId.length==1){
						if(msg.data[0].cityName =='市辖区'){
						
							areaNameStr +='<p>'+msg.data[0].provinceName + "-" + msg.data[0].countyName+'</p></div>';
					}else{
						areaNameStr += '<p>'+msg.data[0].provinceName+ "-" + msg.data[0].cityName+"-"+msg.data[0].countyName+'</p></div>';
					}
			}		
				}else{
					easyDialog.open({
						  container : {
							  header : '提示',
						      content : data.retMsg
						  },
						  autoClose : 2000
						});	
				}
			}
		})
	}
	return areaNameStr;
};
function replaceEmptyItem(arr){
    for(var i=0,len=arr.length;i<len;i++){
        if(!arr[i]|| arr[i]==''){
            arr.splice(i,1);
            len--;
             
        }
    }
};
//点击区域显示编辑、删除
/*function show(){
	$("#firstpane p.menu_head").click(function(){
	     $(this).css({backgroundImage:"url(images/down.png)"}).next("div.menu_body").slideToggle(300).siblings("div.menu_body").slideUp("slow");
	     $(this).siblings().css({backgroundImage:"url(images/left.png)"});
	        });
}*/
// 数据表格参数查询
function doSearch() {
	//InitSupplyAreaData(i);
	searchParames = $('#myform').serialize();
    gridObj.search(searchParames);		
}

// 编辑
function editSupplyArea(id) {
	$("#m1").css("display","block");
	supplyAreaInfo(id);
	localStorage.setItem("supplySaleAreaId", id);
}
//添加
/*function addSupplyArea(id) {
	
	localStorage.setItem("id", id);
	var url='supplyManage/supplyAreaAdd.do?id='+id;
	tl_config.loadToWorkArea(url);
}*/
//删除
/*function delSupplyArea(id,areaId){
	$.ajax({
		url :server_url+'/rest/supplyManage/getSupplyAreaById.do?ran='+Math.random(),
		type:"post",
		data:{id:id},
		success:function(data){
			var areaIds = data.data.supplyArea.data.areaId;
			//console.log(areaIds);
			var Id = areaIds.split(",");
			replaceEmptyItem(Id);
			easyDialog.open({
				  container : {
					  header : '删除确认',
					  content : '您确定要删除此销售区域吗？',
					  yesFn : function(){
						  for(var i=0;i<Id.length;i++){
								if(Id[i]==areaId){
									var ids = Id[i]+",";
									Id = Id.join();
									//console.log(ids);
									Id = areaIds.replaceAll(ids,"");
								}
							}
						  //console.log(Id);return;
				    	$.ajax({
							url:server_url+'/rest/supplyManage/deleteSupplyArea.do?ran='+Math.random()+"&token="+token,
							type:'get',
							data:{
								id:id,
								areaId:Id
								},
							success:function(data){
								if(data.retCode=="0000"){
									//doSearch();
									back();
								}
								else{
									easyDialog.open({
										  container : {
											  header : '提示',
										    content : data.retMsg
										  },
										  autoClose : 2000
										});
									
								} 
								
							}
						})
				    },
				    noFn : true
				  }
				});
		}
	});
	
}*/
/*function getCheckedIds() {
	// values are array
	return gridObj.getCheckedValues('id');
};*/
//返回
function back(){
	localStorage.removeItem("supplySaleAreaId");
	//localStorage.removeItem("areaIdData");
	var url=server_url+'/supplyManage/areaList.do';
	tl_config.last_url=url;
	tl_config.loadToWorkArea(url);
};
//取消
function cancel(){
	$("#m1").css("display","none");
	queryProvince();
	resultLeft = 1;
	resultRight = 1;
	document.getElementById("del").disabled = true;
	//localStorage.removeItem("areaIdData");
};
//确定
function submit(){
	var areaIds = "";
	$('#selectedCountyId li').each(function(i,item){
		areaIds += item.getAttribute("value")+",";	
	});
	console.log(areaIds);
	$.ajax({
		type:"get",
		data:{
			id:localStorage.getItem("supplySaleAreaId"),
			areaId:areaIds
		},
		url:server_url+'/rest/supplyManage/updateById.do?token='+token+'&ran='+Math.random(),
		success:function(){
			easyDialog.open({
				container:{
					header:'温馨提示',
					content:"提交成功",
					yesFn:function(){
						back();
					  }
				}
			});
		},
		error:function(data){
			easyDialog.open({
				container:{
					header:'温馨提示',
					content:data.msg
				},
				autoClose : 2000
			});
		}
	});
};
//供应商销售区域信息
function supplyAreaInfo(id){
	$.ajax({
		type : 'GET',
		contentType : 'application/json',
		async : false,
		data : {
			id : id,
			token:token
		},
		url : server_url+'/rest/supplyManage/getSupplyAreaById.do?ran='+Math.random(),
		dataType : 'json',
		success : function(data) {
			if (data.retCode == "0000") {
					//console.log(data.data.data.areaId);
					//localStorage.setItem("areaIdData", data.data.data.areaId);
					pasteData(data.data.data.areaId);
				} else{
					easyDialog.open({
						container:{
							header:'温馨提示',
							content:data.retMsg
						},
						autoClose : 2000
					});
			}
		}
	});
};
function pasteData(areaIds){
	var areaId = areaIds.split(",");
	replaceEmptyItem(areaId);
	var areaNameStrLi = "";
	for(var k=0;k<areaId.length;k++){
		$.ajax({
			url:server_url+"/rest/supplyManage/getAreaName.do?areaId="+areaId[k],
			type:"get",
			async:false,
			success:function(msg){
				if(msg.retCode=="0000"){
					areaNameStrLi += '<li style="cursor: pointer; background:" onclick="selectEventDels(this);" value='+areaId[k]+'>'+msg.data[0].countyName+';</li>';
				}else{
					easyDialog.open({
						  container : {
							  header : '提示',
						      content : data.retMsg
						  },
						  autoClose : 2000
						});	
				}
			}
		});	
	}
	$('#selectedCountyId').html(areaNameStrLi);
};